<!--
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-07-26 16:12:33
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-08-04 20:54:50
 * @FilePath: \HuiLin\pages\mePages\shopCenter\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<view class="shop-center-container">
		<!-- 头部导航栏 -->
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-content">
					<view class="header-left" @click="closePage">
						<text class="cuIcon-back"></text>
					</view>
					<view class="header-center">
						<text class="header-title">商家中心</text>
					</view>
				</view>
			</template>
		</headerSlot>

		<!-- 主要内容 -->
		<view class="main-content">
			<!-- 店铺信息卡片 -->
			<view class="shop-info-card">
				<view class="shop-header">
					<image class="shop-avatar" :src="shopAvatar" mode="aspectFill"></image>
					<view class="shop-details">
						<text class="shop-name">{{ shopInfo.name || '我的店铺' }}</text>
						<text class="shop-status">{{ shopInfo.status === 'active' ? '营业中' : '休息中' }}</text>
					</view>
				</view>
				<!-- 店铺统计 -->
				<view class="shop-stats">
					<view class="stat-item">
						<text class="stat-number">{{ shopStatistics.totalOrderCount || 0 }}</text>
						<text class="stat-label">总订单数</text>
					</view>
					<view class="stat-item">
						<text class="stat-number">¥{{ formatMoney(shopStatistics.totalAmount || 0) }}</text>
						<text class="stat-label">总收入</text>
					</view>
					<view class="stat-item">
						<text class="stat-number">{{ shopStatistics.todayOrderCount || 0 }}</text>
						<text class="stat-label">今日订单</text>
					</view>
					<view class="stat-item">
						<text class="stat-number">¥{{ formatMoney(shopStatistics.todayAmount || 0) }}</text>
						<text class="stat-label">今日收入</text>
					</view>
				</view>
			</view>

			<!-- 快捷操作 -->
			<view class="quick-actions">
				<view class="action-item" @click="goToOrders">
					<view class="action-icon">📦</view>
					<text class="action-title">订单管理</text>
					<text class="action-desc">处理订单</text>
				</view>
				<!-- <view class="action-item" @click="goToProducts">
					<view class="action-icon">🛍️</view>
					<text class="action-title">商品管理</text>
					<text class="action-desc">管理商品</text>
				</view>
				<view class="action-item" @click="goToSettings">
					<view class="action-icon">⚙️</view>
					<text class="action-title">店铺设置</text>
					<text class="action-desc">店铺配置</text>
				</view>
				<view class="action-item" @click="goToAnalytics">
					<view class="action-icon">📊</view>
					<text class="action-title">数据分析</text>
					<text class="action-desc">查看报表</text>
				</view> -->
			</view>

			<!-- 最近订单 -->
			<view class="recent-orders">
				<view class="section-header">
					<text class="section-title">最近订单</text>
					<text class="view-all" @click="goToOrders">查看全部</text>
				</view>
				<view class="order-list">
					<view class="order-item" v-for="order in recentOrders" :key="order._id"
						@click="goToOrderDetail(order._id)">
						<view class="order-header">
							<text class="order-id">订单号：{{ order.orderNo }}</text>
							<text class="order-status" :class="'status-' + order.status">
								{{ getStatusText(order.status) }}
							</text>
						</view>
						<view class="order-content">
							<text class="product-summary">{{ getProductSummary(order.products) }}</text>
							<text class="order-time">{{ formatDate(order.createTime || order.createdAt) }}</text>
						</view>
						<view class="order-footer">
							<text class="order-amount">¥{{ formatMoney(order.payAmount || order.totalAmount) }}</text>
							<view class="order-actions">
								<text class="action-btn danger"
									v-if="(order.status === 'pending' || order.status === 'paid') && order.status !== 'cancelled'"
									@click.stop="cancelOrder(order._id)">取消订单</text>
								<text class="action-btn" v-if="order.status === 'paid' && order.status !== 'cancelled'"
									@click.stop="confirmShip(order._id)">确认发货</text>
								<text class="action-btn"
									v-if="order.status === 'shipped' && order.status !== 'cancelled' && !isMerchant"
									@click.stop="confirmComplete(order._id)">确认完成</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getShopStatistics,
		getShopOrders,
		confirmShip,
		confirmComplete,
		cancelShopOrder
	} from '@/api/shop.js'
	import headerSlot from '@/components/header-slot.vue'

	export default {
		components: {
			headerSlot
		},
		data() {
			return {
				shopInfo: {},
				shopStatistics: {},
				recentOrders: [],
				loading: false
			}
		},
		computed: {
			shopAvatar() {
				return this.shopInfo.image || '/static/logo-orange.png'
			},
			// 判断是否为商户
			isMerchant() {
				const userInfo = this.$store.state.userInfo || {};
				// 修复：商户应该可以操作自己的店铺订单
				return false; // 暂时禁用商户限制，让商户可以正常操作
			}
		},
		onShow() {
			this.loadShopData()
		},
		methods: {
			// 关闭页面
			closePage() {
				uni.navigateBack()
			},

			// 加载店铺数据
			async loadShopData() {
				try {
					this.loading = true

					// 获取店铺信息
					const userInfo = this.$store.state.userInfo || {};
					if (userInfo.shops && userInfo.shops.length > 0) {
						this.shopInfo = userInfo.shops[0]; // 使用第一个店铺信息
					}

					// 获取店铺统计信息
					const statsRes = await getShopStatistics()
					if (statsRes.data.code === 200) {
						this.shopStatistics = statsRes.data.data
					}

					// 获取最近订单
					const ordersRes = await getShopOrders({
						page: 1,
						limit: 5,
						status: ''
					})
					if (ordersRes.data.code === 200) {
						this.recentOrders = ordersRes.data.data.list || []
					}

				} catch (error) {
					console.error('加载店铺数据失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 格式化金额
			formatMoney(amount) {
				return Number(amount || 0).toFixed(2)
			},

			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return ''
				const date = new Date(dateStr)
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hour = String(date.getHours()).padStart(2, '0')
				const minute = String(date.getMinutes()).padStart(2, '0')
				return `${month}-${day} ${hour}:${minute}`
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'pending': '待付款',
					'paid': '已付款',
					'shipped': '已发货',
					'received': '已送达', // 新增：支持 received 状态
					'delivered': '已送达',
					'completed': '已完成',
					'cancelled': '已取消'
				}
				return statusMap[status] || '未知状态'
			},

			// 获取商品摘要
			getProductSummary(products) {
				if (!products || products.length === 0) return '暂无商品'
				const names = products.map(p => {
					// 支持新的数据结构（productId）和旧的数据结构（直接包含商品信息）
					if (p.productId && p.productId.name) {
						return p.productId.name
					} else if (p.name) {
						return p.name
					}
					return ''
				}).filter(Boolean)
				return names.join('、')
			},

			// 页面跳转方法
			goToOrders() {
				this.$router.smartNavigate({
					url: '/pages/mePages/shopCenter/orders'
				})
			},

			goToProducts() {
				this.$router.smartNavigate({
					url: '/pages/mePages/shopCenter/products'
				})
			},

			goToSettings() {
				this.$router.smartNavigate({
					url: '/pages/mePages/shopCenter/settings'
				})
			},

			goToAnalytics() {
				this.$router.smartNavigate({
					url: '/pages/mePages/shopCenter/analytics'
				})
			},

			goToOrderDetail(orderId) {
				this.$router.smartNavigate({
					url: `/pages/mePages/shopCenter/orderDetail?id=${orderId}`
				})
			},

			// 确认发货
			async confirmShip(orderId) {
				try {
					const result = await confirmShip(orderId)
					// 检查响应结构
					const responseData = result.data || result
					if (responseData && responseData.code === 200) {
						uni.showToast({
							title: '发货成功',
							icon: 'success'
						})
						// 更新本地订单数据
						const orderData = responseData.data.order || responseData.data
						if (orderData) {
							// 找到对应的订单并更新状态
							const orderIndex = this.recentOrders.findIndex(order => order._id === orderId)
							if (orderIndex !== -1) {
								// 使用Vue的响应式方法更新数据
								this.$set(this.recentOrders, orderIndex, orderData)
								// 强制触发视图更新
								this.$forceUpdate()
							}
						} else {
							// 如果没有返回数据，则重新加载
							this.loadShopData()
						}
					} else {
						uni.showToast({
							title: responseData?.message || '发货失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('确认发货失败:', error)
					uni.showToast({
						title: '发货失败',
						icon: 'none'
					})
				}
			},

			// 确认完成
			async confirmComplete(orderId) {
				// 检查是否为商户，商户不允许直接完成订单
				const userInfo = this.$store.state.userInfo || {};
				if (userInfo.shops && userInfo.shops.length > 0) {
					uni.showModal({
						title: '操作限制',
						content: '商户不允许直接完成订单，请联系买家确认收货后自动完成',
						showCancel: false,
						confirmText: '我知道了'
					});
					return;
				}

				try {
					const result = await confirmComplete(orderId)
					// 检查响应结构
					const responseData = result.data || result
					if (responseData && responseData.code === 200) {
						uni.showToast({
							title: '订单已完成',
							icon: 'success'
						})
						// 更新本地订单数据
						const orderData = responseData.data.order || responseData.data
						if (orderData) {
							// 找到对应的订单并更新状态
							const orderIndex = this.recentOrders.findIndex(order => order._id === orderId)
							if (orderIndex !== -1) {
								// 使用Vue的响应式方法更新数据
								this.$set(this.recentOrders, orderIndex, orderData)
								// 强制触发视图更新
								this.$forceUpdate()
							}
						} else {
							// 如果没有返回数据，则重新加载
							this.loadShopData()
						}
					} else {
						uni.showToast({
							title: responseData?.message || '完成失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('确认完成失败:', error)
					uni.showToast({
						title: '完成失败',
						icon: 'none'
					})
				}
			},

			// 取消订单
			async cancelOrder(orderId) {
				uni.showModal({
					title: '取消订单',
					content: '确定要取消订单吗？取消后订单将无法恢复。',
					success: async (res) => {
						if (res.confirm) {
							try {
								const result = await cancelShopOrder(orderId)
								// 检查响应结构
								const responseData = result.data || result
								if (responseData && responseData.code === 200) {
									uni.showToast({
										title: '订单已取消',
										icon: 'success'
									})
									// 更新本地订单数据
									const orderData = responseData.data || result.data?.data
									if (orderData) {
										// 找到对应的订单并更新状态
										const orderIndex = this.recentOrders.findIndex(order => order
											._id === orderId)
										if (orderIndex !== -1) {
											// 使用Vue的响应式方法更新数据
											this.$set(this.recentOrders, orderIndex, orderData)
											// 强制触发视图更新
											this.$forceUpdate()
										}
									} else {
										// 如果没有返回数据，则重新加载
										this.loadShopData()
									}
								} else {
									uni.showToast({
										title: responseData?.message || '取消失败',
										icon: 'none'
									})
								}
							} catch (error) {
								console.error('取消订单失败:', error)
								uni.showToast({
									title: '取消失败',
									icon: 'none'
								})
							}
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.shop-center-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		padding-bottom: 120rpx;
	}

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 32rpx;
		background: transparent;
	}

	.header-left,
	.header-right {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header-center {
		flex: 1;
		text-align: center;
	}

	.header-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.main-content {
		padding: 32rpx;
	}

	.shop-info-card {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		padding: 40rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
		backdrop-filter: blur(10rpx);

		.shop-header {
			display: flex;
			align-items: center;
			margin-bottom: 32rpx;

			.shop-avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				margin-right: 24rpx;
				border: 4rpx solid #fff;
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
			}

			.shop-details {
				flex: 1;

				.shop-name {
					display: block;
					color: #333;
					font-size: 36rpx;
					font-weight: bold;
					margin-bottom: 12rpx;
				}

				.shop-status {
					font-size: 26rpx;
					color: #4caf50;
					background: #e8f5e8;
					padding: 8rpx 16rpx;
					border-radius: 20rpx;
					display: inline-block;
				}
			}
		}

		.shop-stats {
			display: grid;
			grid-template-columns: 1fr 1fr 1fr;
			gap: 32rpx;

			.stat-item {
				text-align: center;
				padding: 24rpx 16rpx;
				background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
				border-radius: 16rpx;
				border: 1rpx solid #e9ecef;

				.stat-number {
					font-size: 36rpx;
					font-weight: bold;
					color: #667eea;
					margin-bottom: 12rpx;
					display: block;
				}

				.stat-label {
					font-size: 26rpx;
					color: #666;
				}
			}
		}
	}

	.quick-actions {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		padding: 40rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
		backdrop-filter: blur(10rpx);

		.action-item {
			display: flex;
			align-items: center;
			padding: 32rpx 0;
			border-bottom: 1rpx solid #f0f0f0;
			transition: all 0.3s ease;

			&:last-child {
				border-bottom: none;
			}

			&:active {
				transform: scale(0.98);
				background: #f8f9fa;
				border-radius: 16rpx;
				margin: 0 -16rpx;
				padding: 32rpx 16rpx;
			}

			.action-icon {
				width: 80rpx;
				height: 80rpx;
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 36rpx;
				margin-right: 24rpx;
				color: #fff;
				box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
			}

			.action-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 8rpx;
				flex: 1;
			}

			.action-desc {
				font-size: 24rpx;
				color: #999;
			}

			&::after {
				content: '>';
				font-size: 32rpx;
				color: #ccc;
				font-weight: bold;
			}
		}
	}

	.recent-orders {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		padding: 40rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
		backdrop-filter: blur(10rpx);

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 32rpx;

			.section-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.view-all {
				font-size: 28rpx;
				color: #667eea;
				padding: 12rpx 24rpx;
				background: rgba(102, 126, 234, 0.1);
				border-radius: 20rpx;
			}
		}

		.order-list {
			.order-item {
				background: #f8f9fa;
				border-radius: 16rpx;
				padding: 32rpx;
				margin-bottom: 24rpx;
				border: 1rpx solid #e9ecef;
				transition: all 0.3s ease;

				&:last-child {
					margin-bottom: 0;
				}

				&:active {
					transform: scale(0.98);
					box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
				}

				.order-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;

					.order-id {
						font-size: 30rpx;
						color: #333;
						font-weight: bold;
					}

					.order-status {
						font-size: 26rpx;
						padding: 8rpx 16rpx;
						border-radius: 16rpx;
						font-weight: bold;

						&.status-pending {
							background: #fff3e0;
							color: #ff9800;
						}

						&.status-paid {
							background: #e8f5e8;
							color: #4caf50;
						}

						&.status-shipped {
							background: #e3f2fd;
							color: #2196f3;
						}

						&.status-delivered {
							background: #e0f2f7;
							color: #00bcd4;
						}

						&.status-completed {
							background: #e8f5e8;
							color: #4caf50;
						}

						&.status-cancelled {
							background: #ffebee;
							color: #f44336;
						}
					}
				}

				.order-content {
					margin-bottom: 20rpx;

					.product-summary {
						font-size: 28rpx;
						color: #666;
						line-height: 1.5;
						margin-bottom: 12rpx;
					}

					.order-time {
						font-size: 26rpx;
						color: #999;
					}
				}

				.order-footer {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.order-amount {
						font-size: 36rpx;
						font-weight: bold;
						color: #f44336;
					}

					.order-actions {
						display: flex;

						.action-btn {
							font-size: 26rpx;
							color: #fff;
							padding: 12rpx 24rpx;
							background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
							border-radius: 20rpx;
							margin-left: 16rpx;
							box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
						}

						.action-btn.danger {
							background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
							box-shadow: 0 4rpx 16rpx rgba(244, 67, 54, 0.3);
						}
					}
				}
			}
		}
	}
</style>